<!-- eslint-disable vue/multi-word-component-names -->
<template>
  <div class="favorites-container">
    <h2>我的收藏</h2>
    
    <div v-if="loading" class="loading-indicator">
      <el-icon><Loading /></el-icon>
      正在加载收藏列表...
    </div>

    <div v-else-if="favorites.length > 0" class="favorites-content">
      <el-alert 
        :title="`共收藏 ${totalFavorites} 条内容`" 
        type="info" 
        show-icon 
        style="margin-bottom: 20px;"
      />
      
      <el-table :data="favorites" border style="width: 100%" stripe>
        <el-table-column prop="sentence_pair_id" label="ID" width="80"></el-table-column>
        <el-table-column prop="text1" label="源语言文本" min-width="200">
          <template #default="scope">
            <div class="text-content">
              <el-tag size="small" type="info">{{ scope.row.lang1 }}</el-tag>
              <div class="text-body">{{ scope.row.text1 }}</div>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="text2" label="目标语言文本" min-width="200">
          <template #default="scope">
            <div class="text-content">
              <el-tag size="small" type="success">{{ scope.row.lang2 }}</el-tag>
              <div class="text-body">{{ scope.row.text2 }}</div>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="source" label="来源" width="120"></el-table-column>
        <el-table-column prop="created_at" label="收藏时间" width="180">
          <template #default="scope">
            {{ formatDate(scope.row.created_at) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="100" align="center">
          <template #default="scope">
            <el-popconfirm
              title="确定要取消收藏吗？"
              @confirm="removeFavorite(scope.row)"
            >
              <template #reference>
                <el-button
                  type="danger"
                  :icon="Delete"
                  circle
                  :loading="scope.row.removeLoading"
                  title="取消收藏"
                />
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
      
      <div class="pagination-footer">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="totalFavorites"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>
    
    <div v-else class="empty-favorites">
      <el-empty description="还没有收藏任何内容">
        <el-button type="primary" @click="goToRetrieve">去检索</el-button>
      </el-empty>
    </div>
    
    <el-alert 
      v-if="errorMessage" 
      :title="errorMessage" 
      type="error" 
      show-icon 
      closable
      @close="errorMessage = ''"
      style="margin-top: 20px;"
    />
  </div>
    <div class="back-btn">
    <back-button></back-button>
  </div>
</template>

<script setup name="MyFavorites">
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { Loading, Delete } from '@element-plus/icons-vue'
import { favorites as favoritesApi } from '@/api'
import BackButton from '@/components/BackButton.vue'
import '@/assets/common.css'

const router = useRouter()
const loading = ref(false)
const favorites = ref([])
const errorMessage = ref('')
const currentPage = ref(1)
const pageSize = ref(10)
const totalFavorites = ref(0)

/**
 * 加载收藏列表
 */
const loadFavorites = async () => {
  loading.value = true
  errorMessage.value = ''
  
  try {
    const response = await favoritesApi.list({
      page: currentPage.value,
      per_page: pageSize.value
    })
    
    if (response.data.status === 'success') {
      favorites.value = response.data.data.favorites.map(item => ({
        ...item,
        removeLoading: false
      }))
      totalFavorites.value = response.data.data.total
      currentPage.value = response.data.data.page
      pageSize.value = response.data.data.per_page
    }
  } catch (error) {
    console.error('加载收藏列表失败:', error)
    errorMessage.value = error.response?.data?.message || error.message || '加载收藏列表失败'
    
    // 如果是401未授权，跳转到登录页
    if (error.response?.status === 401) {
      ElMessage.warning('请先登录')
      router.push('/login')
    }
  } finally {
    loading.value = false
  }
}

/**
 * 取消收藏
 * @param {Object} item - 收藏项
 */
const removeFavorite = async (item) => {
  item.removeLoading = true
  
  try {
    await favoritesApi.remove(item.favorite_id)
    ElMessage.success('取消收藏成功')
    
    // 重新加载列表
    await loadFavorites()
  } catch (error) {
    console.error('取消收藏失败:', error)
    const message = error.response?.data?.message || error.message || '取消收藏失败'
    ElMessage.error(message)
    item.removeLoading = false
  }
}

/**
 * 格式化日期
 * @param {string} dateString - ISO日期字符串
 * @returns {string} 格式化后的日期
 */
const formatDate = (dateString) => {
  if (!dateString) return '-'
  const date = new Date(dateString)
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  })
}

/**
 * 跳转到检索页面
 */
const goToRetrieve = () => {
  router.push('/retrieve')
}

/**
 * 分页大小改变
 */
const handleSizeChange = (newSize) => {
  pageSize.value = newSize
  loadFavorites()
}

/**
 * 当前页改变
 */
const handleCurrentChange = (newPage) => {
  currentPage.value = newPage
  loadFavorites()
}

// 页面加载时获取收藏列表
onMounted(() => {
  loadFavorites()
})
</script>

<style scoped>
.favorites-container {
  max-width: 1400px;
  margin: 0 auto;
  padding: 20px;
}

.loading-indicator {
  margin: 50px 0;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #606266;
  font-size: 16px;
}

.favorites-content {
  margin-top: 20px;
}

.text-content {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.text-body {
  white-space: pre-wrap;
  word-break: break-word;
  line-height: 1.6;
  color: #303133;
}

.pagination-footer {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.empty-favorites {
  margin-top: 60px;
  text-align: center;
}
</style>

